<template>
  <BeModal v-model:open="modalVisible" centered width="60%" title="新增筛选条件" @ok="onOk" @cancel="handleCancel" confirmText="确定" customClose :showFooter="true">
    <div class="fields-container">
      <!-- 循环渲染所有查询字段 -->
      <div v-for="(field, index) in filteredFields" :key="index" class="field-item" :class="{ selected: selectedFields.includes(field.prop) }" @click="toggleSelection(field.prop)">
        {{ field.label }}
      </div>
    </div>
  </BeModal>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { queryFields, definedFields } from './data'
const emit = defineEmits(['update:showModal', 'saveSelectedFields'])

interface Props {
  showModal: boolean
}
interface FieldItem {
  prop: string
  label: string
}
const props = withDefaults(defineProps<Props>(), {
  showModal: false
})
const modalVisible = ref(false)
const filteredFields = computed(() => {
  const definedFieldProps = definedFields.map((field) => field.prop)
  const result = queryFields.slice(1).filter((f) => !definedFieldProps.includes(f.prop))
  return result
})
// 存储选中的字段prop
const selectedFields = ref<string[]>([])

// 切换字段选中状态
const toggleSelection = (prop: string) => {
  const index = selectedFields.value.indexOf(prop)
  if (index > -1) {
    // 取消选中
    selectedFields.value.splice(index, 1)
  } else {
    // 选中字段
    selectedFields.value.push(prop)
  }
}

// 确定按钮回调
const onOk = () => {
  if (selectedFields.value.length === 0) {
    return message.warning('请选择筛选查询条件字段！')
  }
  // 传递选中的字段给父组件
  emit('saveSelectedFields', JSON.parse(JSON.stringify(selectedFields.value)))
  selectedFields.value = []
  // 关闭模态框
  emit('update:showModal', false)
  modalVisible.value = false
}

// 取消按钮回调
const handleCancel = () => {
  console.log('取消')
  selectedFields.value = []
  emit('update:showModal', false)
  modalVisible.value = false
}
watch(
  () => props.showModal,
  (newVal) => {
    modalVisible.value = newVal
  },
  { immediate: true }
)
</script>
<style lang="scss" scoped>
.fields-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 12px 0;
  // overflow-y: auto;
  // scrollbar-width: thin;

  // &::-webkit-scrollbar {
  //   width: 6px;
  // }

  // &::-webkit-scrollbar-thumb {
  //   background-color: #ddd;
  //   border-radius: 3px;
  // }
}

.field-item {
  padding: 6px 14px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    border-color: #1890ff;
    color: #1890ff;
  }
}

// 选中状态样式（主题色）
.selected {
  border-color: #1890ff !important;
  color: #1890ff !important;
  background-color: rgba(24, 144, 255, 0.08);
  font-weight: 500;
}
</style>
